package com.easychat.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.easychat.entity.enums.ResponseCodeEnum;
import com.easychat.exception.BusinessException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

public class JsonUtils {
    private static final Logger logger = LoggerFactory.getLogger(JsonUtils.class);

    private static SerializerFeature[] FEATURES = new SerializerFeature[]{SerializerFeature.WriteMapNullValue};

    public static String convertObj2Json(Object obj){
        // 将对象转换为JSON字符串，并指定特定的特性集
        return JSON.toJSONString(obj,FEATURES);
    }

    public static <T> T convertJson2obj(String json,Class<T> classz){
        try {
            return JSONObject.parseObject(json,classz);
        }catch (Exception e){
            logger.error("convertJson2obj异常，json：{}",json);
            throw new BusinessException(ResponseCodeEnum.CODE_601);
        }
    }

    public static <T> List<T> convertJsonArray2List(String json, Class<T> classz){
        try {
            return JSONObject.parseArray(json,classz);
        }catch (Exception e){
            logger.error("convertJsonArray2List，json：{}",json,e);
            throw new BusinessException(ResponseCodeEnum.CODE_601);
        }
    }
}